package cn.lingyangwl.framework.tool.core.jar;

import cn.lingyangwl.framework.tool.core.exception.Assert;
import cn.lingyangwl.framework.tool.core.MD5Utils;
import cn.lingyangwl.framework.tool.core.StringUtils;

import java.security.NoSuchAlgorithmException;

/**
 * @author shenguangyang
 */
public class CopyResourcesInfo {
    private ResourcesInfo resourcesInfo;

    /**
     * 自定义目录路径
     */
    private String customDirPath;

    private String dirName;

    protected void check() {
        Assert.notNull(resourcesInfo, "resourcesInfo is null");
    }

    protected ResourcesInfo getResourcesInfo() {
        return resourcesInfo;
    }

    public String getCustomDirPath() {
        return customDirPath;
    }

    public String getDirName() {
        return dirName;
    }

    public static CopyResourcesInfoBuilder builder() {
        return new CopyResourcesInfoBuilder();
    }


    public static final class CopyResourcesInfoBuilder {
        private ResourcesInfo resourcesInfo;
        private String customDirPath;
        private String dirName;

        private CopyResourcesInfoBuilder() {
        }


        public CopyResourcesInfoBuilder resourcesInfo(ResourcesInfo resourcesInfo) {
            this.resourcesInfo = resourcesInfo;
            return this;
        }

        public CopyResourcesInfoBuilder customDirPath(String customDirPath) {
            this.customDirPath = customDirPath;
            return this;
        }

        public CopyResourcesInfoBuilder dirName(String dirName) {
            this.dirName = dirName;
            return this;
        }

        public CopyResourcesInfo build() {
            Assert.notNull(this.resourcesInfo, "resourcesInfo is null");
            CopyResourcesInfo copyResourcesInfo = new CopyResourcesInfo();
            copyResourcesInfo.customDirPath = this.customDirPath;
            try {
                copyResourcesInfo.dirName = StringUtils.isEmpty(this.dirName) ? MD5Utils.md5(this.resourcesInfo.getClass().getName()) : this.dirName;
            } catch (NoSuchAlgorithmException e) {
                throw new RuntimeException(e);
            }
            copyResourcesInfo.resourcesInfo = this.resourcesInfo;

            if (this.resourcesInfo.classPaths() != null) {
                for (String path : this.resourcesInfo.classPaths()) {
                    if (!StringUtils.isEmpty(path)) {
                        // 判断是否包含 \, 包含则报错
                        if (path.contains("\\") || path.startsWith("/")) {
                            throw new RuntimeException("illegal classPath [" + path + "], Can only be split with / and cannot start with /");
                        }
                    }
                }
            }
            return copyResourcesInfo;
        }
    }

    public static void main(String[] args) {
        System.out.println("/".substring(1));
    }
}
